08. Exercise: Reflection API

Exercise: Reflection API

Testing with Reflection: Part 2

It's time to continue developing your in-house unit testing framework!

You already defined the @Test annotation to mark unit test methods, and you created the UnitTest interface, which provides two abstract methods:

  • void beforeEachTest() runs before each unit test to set up the test environment; and
  • void afterEachTest() runs after each unit test to clean up the test environment

Now, it's time to fill out TestRunner.java which decides which tests to run (by finding methods annotated with @Test) and then reports the test results.

The TestRunner has already been partially filled in for you. Iterate through TESTS (the static list of test classes) and use the reflection API to do the following:

  1. Make sure the test class implements UnitTest. You can do this with Class#isAssignableFrom()).
  2. Create an instance of the test class and cast it to be a UnitTest. You can do this by calling Class#getConstructor()) with no arguments, and then calling the newInstance()) method.
  3. For each method with the @Test annotation:
    • Call UnitTest#beforeEachTest(), then invoke the test method (use Method#invoke()), and then call UnitTest#afterEachTest().
    • If the test threw any errors, record that test as having failed. Otherwise, record that test as having passed.

At the end of the main() method, you should print out the results (see below for an example).

Compile and run the test runner to make sure it works. (Note: One unit test in CalculatorTest.java should intentionally fail — this is so that you can see what happens for both passing and failing tests.)

javac TestRunner.java
java -ea TestRunner

Note: See the -ea JVM option? That stands for "enable assertions", which makes the assert statements in CalculatorTest.java actually throw AssertionErrors. There are much more robust assertion libraries out there (you'll see one such library in the course project), but for the purposes of this exercise, assert keeps things simple.

After running the program, aim for output similar to this:

Passed tests: [CalculatorTest#testAddition]
FAILED tests: [CalculatorTest#testSubtraction]

TODO List

Task List:

Task Feedback:

Congratulations! You built a simple, yet functional testing framework using your own annotations and the Reflection API!

Code

If you need a code on the https://github.com/udacity.

  • userCode:

    export PATH=/data/jdk-15.0.1/bin:$PATH
    export JAVA_HOME=/data/jdk-15.0.1/bin